<template>
  <div class="app-container">
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="pd" ref="pd" >
        <el-form-item prop="wjlx">
          <!--<el-input v-model="pd.wjlx" placeholder="图片类型" style="width:300px;"/>-->

          <el-select v-model="pd.wjlx" placeholder="请选择图片类型">
            <el-option
              v-for="item in wjlxDicts"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  @click="fetchData">查询</el-button>  <!--icon="el-icon-search"-->
        </el-form-item>
        <el-form-item>
          <el-button  @click="resetForm('pd')">重置</el-button>
        </el-form-item>

        <br>
        <el-form-item><!--@click="handleAdd" icon="el-icon-edit"-->
          <el-button type="primary"  icon="el-icon-plus"  style="width:100px;" @click="handleAdd">添加</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <el-table
      v-loading="listLoading"
      :data="users"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row>
<!--    <el-table
      :data="users"
      stripe
      style="width: 100%">-->
      <el-table-column align="center" label="ID" width="95"  fixed>
        <template slot-scope="scope">
          {{ scope.$index }}
        </template>
      </el-table-column>
      <el-table-column label="图片" width="360" align="center">
        <template slot-scope="scope">
          <span  v-if="scope.row.fileurl!=''">
             <img :src="scope.row.fileurl"  min-width="70" height="70" />
          </span>
        </template>
      </el-table-column>
      <el-table-column label="图片路径" width="480" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.fileurl }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片类型" width="180" align="center" :formatter="formatScbj">
        <template slot-scope="scope" >
          <span v-for="item in wjlxDicts">
            <span v-if="item.code===scope.row.wjlx ">{{item.name}}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.filename }}
        </template>
      </el-table-column>
      <!--<el-table-column :formatter="formatScbj" pro="scbj" name="status-col" label="账户启用状态" width="210" align="center" />
      <el-table-column align="center" prop="created_at" label="修改时间" width="300">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.xgsj }}</span>
        </template>
      </el-table-column>-->
      <el-table-column label="操作" align="center">
        <template scope="scope">
          <!--<el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>-->
          <el-button size="mini" type="danger" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!--<el-button :disabled="users.length===0" type="danger" @click="batchRemove">批量删除</el-button>-->
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="showCount"
        :page-count="totalPage"
        :total="totalResult"
        style="float:right;"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>

    </el-col>

    <!--新增界面-->
    <!-- Form -->
    <!--<el-button type="text" @click="dialogFormVisible = true">打开嵌套表单的 Dialog</el-button>-->

    <el-dialog title="新增图片" :visible.sync="dialogFormVisible">
      <el-form :model="form"  ref="form">
        <el-form-item label="图片名称：" :label-width="formLabelWidth">
          <el-input v-model="form.filename" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="图片类型：" :label-width="formLabelWidth">
          <el-select v-model="form.wjlx" placeholder="请选择">
            <el-option
              v-for="item in wjlxDicts"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
         <el-form-item  label="标题图片：" :label-width="formLabelWidth" pro="fileurl">
        <el-upload   v-model="form.fileurl"
                     class="upload-demo"
                     :on-preview="handlePreview"
                     :on-remove="handleRemove"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload"
                     :before-remove="beforeRemove"
                     multiple
                     :limit="3"
                     :on-exceed="handleExceed"
                     action="https://www.laidianba.net.cn:9600/uploadFile"
                     :file-list="fileList"
                     list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif/bmp文件，且不超过2M</div>
        </el-upload>
      </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"  @click.native="submitForm" :loading="addLoading">确 定</el-button>
      </div>
    </el-dialog>

  </div>

</template>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<script>
import util from '@/common/js/util'
import { getImagePgListPage, getWjlxDictPgListPage,savaFile, delFile} from '@/api/image'
export default {

  data() {
    return {
      imageUrl: '',
      currentPage: 1,
      currentResult: 0,
      entityOrField: true,
      pageStr: 'string',
      pd: {
        wjlx: ''
      },
      showCount: 5,
      totalPage: 0,
      totalResult: 0,
      users: [],
      listLoading: true,
      fileList: [],
      addLoading: false,
      wjlxDicts: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        wjlx: '',
        filename: '',
        fileurl: ''

      },
      formLabelWidth: '120px'

    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 是否启用转换
    formatScbj: function(row, column) {
      return row.scbj === 1 ? '未启用' : row.scbj === 0 ? '已启用' : '未知'
    },
    formatScbjValue: function(value) {
      return value === 1 ? '未启用' : value === 0 ? '已启用' : '未知'
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleCurrentChange(currentPage) {
      console.log(`当前页: ${currentPage}`)
      this.currentPage = currentPage
      this.fetchData()
    },
    handleSizeChange(showCount) {
      console.log(`每页 ${showCount} 条`)
      this.showCount = showCount
      this.fetchData()
    },
    // 列表
    fetchData() {
      const page = {
        currentPage: this.currentPage,
        currentResult: 0,
        entityOrField: true,
        pageStr: 'string',
        pd: {
          wjlx: this.pd.wjlx
        },
        showCount: this.showCount,
        totalPage: 0,
        totalResult: 0
      }
      getWjlxDictPgListPage(page).then(response => {
        if (response.data.error === null) {
          this.wjlxDicts = response.data.data.list
          this.listLoading = false
        } else {
          // this.loading = false
          this.$message({
            message: response.data.error.text,
            type: 'error'
          })
        }
      })
      this.listLoading = true
      getImagePgListPage(page).then(response => {
        if (response.data.reason === null) {
          this.currentPage = response.data.result.page.currentPage
          this.totalPage = response.data.result.page.totalPage
          this.totalResult = response.data.result.page.totalResult
          this.users = response.data.result.list
          // this.page = response.data.result.page
          this.listLoading = false
        } else {
          this.loading = false
          this.$message({
            message: response.data.reason.text,
            type: 'error'
          })
        }
      })
    },

    // 显示新增界面
    handleAdd: function() {
      console.log(this.addFormVisible)
      this.dialogFormVisible = true
      this.addForm = {
        filename: '',
        fileurl: '',
        wjlx: ''
    }
    },
    // 新增

    submitForm: function() {
      console.log("文件列表"+this.fileList);
      let self = this;
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true
            // NProgress.start();
            console.log(this.form);
            const para = Object.assign({}, this.form)
            console.log('para', para);

              //新增
              savaFile(para).then((res) => {
                console.log("res");
                console.log(res);
                this.addLoading = false;
                this.dialogFormVisible=false;
                // NProgress.done();
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.$refs['form'].resetFields()
                this.fetchData()
              }).catch(function (error) {
                self.addLoading = false;
                console.log('发生错误！', error);
                //已由拦截器提醒
                // self.$message({
                //   message: '发生错误 ：'+error,
                //   type: 'error'
                // })

              })

          })
        }
      })
    },
    //删除
    handleDel: function (index, row) {
      console.log('删除',index);
      console.log('删除row',row);
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let para = {
          id: row.id,
          fileurl:row.fileurl
        };
        delFile(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.fetchData();
          this.$message({
            message: '删除成功',
            type: 'success'
          });

        });
      }).catch(() => {
        this.listLoading = false;
      });
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
      console.log('delfile',file);
      let para = {
        fileurl:file.url
      };
      delFile(para).then((res) => {
        console.log('删除返回值',res);
        let fileurl = this.form.fileurl;
        console.log('picture',fileurl.split(','));
        if (fileurl!== '') {
          let picture =fileurl.split(',');
          picture.forEach((item,index)=>{
            console.log('item',item)
            if (file.url === item) {
              picture.splice(index,1);
              this.form.fileurl = picture.join(',');
              console.log('删除后的图片',this.form.fileurl)
            }
          })
        }
      });

    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      // this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      this.$message.warning(`最多可上传 3 个文件！`);
    },
    beforeRemove(file, fileList) {
      return true;
      // return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleAvatarSuccess(res, file) {
      console.log(res,res.data.url);
      console.log(file, file.url);
      file.url =res.data.url
      console.log('file.url',file.url);
      if(this.form.fileurl==''){
        this.form.fileurl = res.data.url;
      }else {
        this.form.fileurl =   this.form.fileurl +','+res.data.url;
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isGIF = file.type === 'image/gif';
      const isPNG = file.type === 'image/png';
      const isBMP = file.type === 'image/bmp';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isGIF && !isPNG && !isBMP) {
        this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
    }


  }

}
</script>
